/*
* 商品系列公共js库
* */
;(function ($, window, document, undefined) {
    var numberItem = function (ele, opt) {
        this.$element = ele;           //获取到的jQuery对象console.log(this);
        //设置默认参数
        this.defaults = {
            'price': '0',
            'number': 1,      //选中的sku class
            'min': 1,        //禁用按钮class
            'max': false,
            'step': 1,
            'add': '.add',
            'sub': '.sub',
            setPrice: function (price) {
                //设置价格函数
                console.log('目前单价' + price)
            },
            setMoney: function (money) {
                //设置总价
                console.log('目前总价' + money);
            },
        };
        this.options = $.extend({}, this.defaults, opt);
        var _ = this;
        this.validate = function (number) {
            if (number < _.options.min) {
                return false;
            }
            if (_.options.max && number > _.options.max) {
                return false;
            }
            return true;
        };
        /**
         * 修改数量
         * @param type 修改的方式 1加 -1 减
         */
        this.change = function (type) {
            var number = parseInt(_.options.number + _.options.step*type);
            if (_.validate(number)) {
                $(_.$element).find('input').val(number);
                _.options.number = number;
                _.format_goods_price()
            }
        };
        this.format_goods_price = function () {
            var simplePrice = 0;
            if (_.options.price.indexOf(':') > 0) {
                var goodsPrice = _.options.price.split(',');
                for (var i in goodsPrice) {
                    var simple = goodsPrice[i].split(':');
                    if (parseInt(i) === 0) {
                        simplePrice = simple[1];
                    } else {
                        if (parseInt(simple[0]) <= parseInt(_.options.number)) {
                            simplePrice = simple[1];
                        }
                    }
                }
            } else {
                simplePrice = _.options.price;
            }
            _.options.setPrice(simplePrice);
            _.options.setMoney(simplePrice * _.options.number);
        }
    };
    numberItem.prototype = {
        init: function () {
            var _ = this;
            $(this.$element).find('input').val(_.options.number);
            _.format_goods_price();
            $(this.$element).on('click',_.options.add,function () {
                _.change(1);
            });
            $(this.$element).on('click',_.options.sub,function () {
                _.change(-1);
            })
        }
    };
    $.fn.num = function (option) {
        var number = new numberItem(this, option);
        return number.init();
    }
})(jQuery, window, document);
;(function ($, window, document, undefined) {
    /**
     * 页面显示sku列表
     * @param ele 操作的元素
     * @param opt 参数 格式@param
     *                      sku 当前的sku字符串，格式 'sku1;sku2;sku3'
     *                      keys sku列表格式{
                            'attr_name':['10','11'],
                            'attr_name':['20','21','22','23'],
                            'attr_name':['30','31','32'],
                            'attr_name':['40','41']
                           }
     * sku_list sku列表以及数量 格式[
     {'sku_key':'10;20;30;40','sku_id':120,sku_sn:'111',
     goods_id:'32434',market_price:'10.2',
     goods_price:'11',price:11,goods_stock:'100',
     goods_weight:'0.1',min:'10',fulltitle:'asdas',
     goods_name:'dsfds',sku_name:'sadasd'},
     {'sku_key':'10;20;30;40','sku_id':120,sku_sn:'111',
     goods_id:'32434',market_price:'10.2',
     goods_price:'11',price:11,goods_stock:'100',
     goods_weight:'0.1',min:'10',fulltitle:'asdas',
     goods_name:'dsfds',sku_name:'sadasd'}
     ]
     *                      templateId 模板引擎模板id，在模板中会传入keys，active和sku_in 三个参数，其中keys就是传入的keys，循环就可以将所有的sku展示出来。
     *                      active是当前的sku选择状态，可以判断active.indexOf('当前循环的keys')>=0来确定是否选中
     *                      sku_in是当前选中状态下所有可以选择的sku，可以通关判断 sku_in.indexOf('当前循环的key')===-1来判断，如果为true，则该sku在当前sku下无库存

     *
     */
    var skuItem = function (ele, opt) {
        /**
         * opt中必须包含
         * {
         *  'sku': sku,            //当前选择的sku
         *  'keys': keys,        //所有sku列表
         *  'sku_list': sku_list,    //sku列表以及数量等信息
         *}
         *
         */
        this.$element = ele;           //获取到的jQuery对象console.log(this);
        //设置默认参数
        this.defaults = {
            'active': 'active',      //选中的sku class
            'disable': 'disable',        //禁用按钮class
            'template': '{{ each keys as key name}}\n' +  //生成html的模板，使用arttemplate模板引擎
            '    <div class="sku-row">\n' +
            '        <span class="row-tit">{{ name}}</span>\n' +
            '        {{ each key as k}}\n' +
            '        <button type="button"\n' +
            '                class="sku-item {{ if active.indexOf(k)>=0}} active {{ /if}}"\n' +
            '                {{ if sku_in.indexOf(k)===-1}} disabled {{ /if}}>{{ k}}</button>\n' +
            '        {{ /each}}\n' +
            '    </div>\n' +
            '{{ /each}}',
            setInfo: function (info) {  //当前选择的sku信息处理函数
                console.log(info);
            }
        };
        this.options = $.extend({}, this.defaults, opt);
        var _ = this;
        //将所有sku转换成数组
        this.getArr = function () {
            var sku_arr = [];
            for (var i in _.options.sku_list) {
                sku_arr.push(_.options.sku_list[i]['sku_key'].split(';'));
            }
            return sku_arr;
        };
        //将当前选择转换为数组
        this.sku_split = function () {
            return _.options.sku.split(';');
        };
        //数组去重
        this.removeDuplicatedItem3 = function (ar) {
            var ret = [];

            ar.forEach(function (e, i, ar) {
                if (ar.indexOf(e) === i) {
                    ret.push(e);
                }
            });

            return ret;
        };
        //获取当前选择情况下的html
        this.getHtml = function () {
            var sku_in = [];
            for (var s in _.sku_split()) {
                var sku_now = _.sku_split();
                sku_now.splice(s, 1);
                var arr = _.getArr();
                for (var i in arr) {
                    if (_.isContained(arr[i], sku_now)) {
                        sku_in = sku_in.concat(arr[i]);
                    }
                }
            }
            sku_in = _.removeDuplicatedItem3(sku_in);
            var render = template.compile(_.options.template);
            return render({keys: _.options.keys, active: _.sku_split(), sku_in: sku_in});
        };
        //获取当前选中sku的信息
        this.getInfo = function () {
            for (var i in _.options.sku_list) {
                if (_.options.sku_list[i]['sku_key'] === _.options.sku) {
                    _.options.setInfo(_.options.sku_list[i]);
                    return _.options.sku_list[i]
                }
            }
        };
        this.isContained = function (a, b) {
            if (!(a instanceof Array) || !(b instanceof Array)) return false;
            if (a.length < b.length) return false;
            var aStr = a.toString();
            for (var i = 0, len = b.length; i < len; i++) {
                if (aStr.indexOf(b[i]) == -1) return false;
            }
            return true;
        }
    };
    //定义goodsItem的方法
    skuItem.prototype = {
        init: function () {
            var _ = this;
            this.$element.empty().html(this.getHtml());
            $(this.$element).on('click', 'button', function () {
                $(this).addClass(_.options.active).siblings().removeClass(_.options.active);
                var sku_now = [];
                $(_.$element).find(' .' + _.options['active']).each(function () {
                    sku_now.push($(this).text());
                });
                _.options.sku = sku_now.join(';');
                _.getInfo();
                _.$element.empty().html(_.getHtml());
            });
            _.getInfo();
        }
    };
    $.fn.skuItem = function (options) {
        var goods = new skuItem(this, options);
        return goods.init();
    }
})(jQuery, window, document);